// ==UserScript==
// @name           Craigslist Quick Page Viewer
// @namespace      derekdahmer.com
// @description    Clicking a link in a CraigsList list will toggle open and closed the linked page's content in a div directly below the link.  Designed by Derek Dahmer.  Released under the MIT license.
// @include        *.craigslist.org*
// ==/UserScript==

// Add jQuery
var greasemonkey_jquery = document.createElement('script');
greasemonkey_jquery.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js';
greasemonkey_jquery.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(greasemonkey_jquery);

// Check if jQuery loaded
function wait_until_jquery_loaded() {
	if(typeof unsafeWindow.jQuery == 'undefined') { window.setTimeout(wait_until_jquery_loaded,10); }
	else { $ = unsafeWindow.jQuery; letsJQuery(); }
}
wait_until_jquery_loaded();

// All your GM code must be inside this function
function letsJQuery() {
	$(function() {
		
		// Initial data
		$(window).data("current_row_index",0);
		$(window).data("rows",$("blockquote > p"));
		if ($(window).data("rows").length == 0) { console.log('Could not find any listings'); }
		
		// Helper function for loading data in a div
		var load_html = function(div,url) {
			$contents_div = $(div).find("div.pagecontents");
			if (!$contents_div.data("loaded")) {
				// Load just the inner content
				$contents_div.load(url + " #userbody");
				$contents_div.data("loaded",true);
			}
		}
		
		
		
		// For each row listing...
		$("blockquote > p").each(function() {
			var $p = $(this); // Each row
			var $a = $($(this).find("a:first")); // The main link
			if ($a.length == 0) { console.log("Couldn't find blockquote > p > a:first"); }
			
			// Exclude "next 100 postings"
			if (!$p.children().is("a")) {
				return;
			}
			
			// ADD PERMALINK
			// Get info from link
			var url = $a.attr("href");
			
			// Create new permanent link straight to page
			var newlink = $("<a class='permalink'>Permalink</a>").attr("href",url).css('margin-left','15px');
			
			// Add to row
			if ($p.find("br.c").length > 0) { // furniture section has this
				$p.find("br.c").before(newlink);
			} else {
				$p.append(newlink);
			}
			
			// CREATE DIV
			// Make the first link on the line float left so the div floating works right
			$a.css("float","left");
			
			// Add an invisible div under each list item to hold linked pages' html
			var $div = $("<div class='preview'>Loading</div>")
				.data("loaded",false)
				.hide();
			$div = $div.append("<BR style='clear:both;' />");
			$div = $div.append("<div class='pagecontents'></div>")
				.css('border','3px solid black')
				.css('padding','5px')
				.css('margin-left','15px')
				.css('margin-bottom','15px')
				.css('background-color','#DDEDED')
				.css('float','left')
				.css('clear','both');
			
			// Add to the end
			if ($p.find("br.c").length > 0) { // furniture section has this
				$p.find("br.c").before($div);
			} else {
				$p.append($div);
			}			
			
			// CLICK HANDLER
			$a.click(function(e) {
				// Get info from link
				var url = $(this).attr("href");
				
				// Load and add HTML to the div we created
				$div = $($(this).parent().find("div.preview"));
				load_html($div,url);
				
				// Toggle visibility
				$div.toggle();
				return false;
			});	
			
		});

		
		// Create the keyboard controls
		$(window).keydown(function(event) {
			var win = $(window);
			var $current_div, $next_div;
			var doTransition = false;
			if (!event.altKey) {
				return true;
			}
			switch (event.keyCode) {
				case 74: // j
					var current_row_index = win.data("current_row_index");
					if (current_row_index > 0) {
						// Find loading divs
						$current_div = $($(win.data("rows").get(current_row_index)).find('div.preview'));
						$next_div = $($(win.data("rows").get(current_row_index - 1)).find('div.preview'));
						
						win.data("current_row_index", current_row_index-1);
						doTransition = true;
					}
					break;
				case 75: // k
					var current_row_index = win.data("current_row_index");
					if (current_row_index < win.data("rows").length) {
						// Find loading divs
						$current_div = $($(win.data("rows").get(current_row_index)).find('div.preview'));
						$next_div = $($(win.data("rows").get(current_row_index + 1)).find('div.preview'));
						
						win.data("current_row_index", current_row_index+1);
						doTransition = true;
					}
					break;
			}
			
			// Do the transition
			if (doTransition) {
				// Load the data
				var url = $next_div.parent().find('a:first').attr("href");
				load_html($next_div,url);
				
				// Swap which is visible
				$current_div.hide();
				$current_div.parent().css("font-weight","");
				$next_div.show();
				$next_div.parent().css("font-weight","bold");
			}
			
			if (event.keyCode == 74 || event.keyCode == 75) {
				// Key has been handled
				return false;
			}
		});
	});	
}
